from http import server
from random import randint, random
from location_init import *
import math,time

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import position_config as pc


def init_label(ax,is_simulate):
    ax.set_xlabel("x")
    ax.set_ylabel("y")
    ax.set_aspect('equal')
    if pc.full_map:
        base = 1
        if (is_simulate): base*=2
        ax.set_xlim([0, pc.E*base])
        ax.set_ylim([0, pc.E*base])
    else:
        ax.set_xlim([pc.partx, pc.partx+pc.size])
        ax.set_ylim([pc.party, pc.party+pc.size])
    
    title_str = "{}".format(
        "Grd" if not is_simulate else "Sim"
    )
    ax.set_title(title_str)



def create_pos_fig(ax,pos,color = 'b',arrow_color = 'k',marker='o',is_latest=False,aw_len=20):
    if (ax is None): return 
    '''
    return (scatter, arrow) to show a car's position
    '''
    # assert(isinstance(pos,Position))
    x,y,rad = pos['x'],pos['y'],pos['rad']
    # print("pos = ",pos)
    dx = aw_len*math.cos(rad)
    dy = aw_len*math.sin(rad)

    if (not is_latest):
        color = 'gray'
        pt = ax.scatter([x],[y],
                        s=50,c=color,marker=marker,alpha=0.5)
    else:
        pt = ax.scatter([x],[y],
                        s=50,c=color,marker=marker,alpha=0.5)
        pt_aw =ax.arrow(x,y,dx,dy,color=arrow_color,width=1)

def random_loc():
    x=randint(0,pc.E)
    y=randint(0,pc.E)
    rad = math.radians(randint(0,360))
    return {'x':x,'y':y,'rad':rad}

def animate_update_grd(fid):
    global axes

    # loc_list = [
    #     location_server.get_grd_display_info(5),
    #     location_server.get_sim_display_info(5)
    #     ]
    ax = axes[0]
    ax.clear()
    init_label(ax,is_simulate=False)
    create_pos_fig(ax,random_loc(),is_latest=False)


def animate_update_sim(fid):
    global axes

    # loc_list = [
    #     location_server.get_grd_display_info(5),
    #     location_server.get_sim_display_info(5)
    #     ]
    ax = axes[1]
    ax.clear()
    init_label(ax,is_simulate=True)
    create_pos_fig(ax,random_loc(),is_latest=True)


def raise_plt():
    global axes
    fig, axes = plt.subplots(1, 2, figsize=(pc.plt_size*2,pc.plt_size))
    axes = axes.ravel()

    global ax_color 
    ax_color = [
        {'color':'b','arrow_color' : 'k','marker':'o'},
        {'color':'r','arrow_color' : 'k','marker':'o'}
    ]

    ani_grd = FuncAnimation(fig=fig, func=animate_update_grd, frames=10)
    ani_sim = FuncAnimation(fig=fig, func=animate_update_sim, frames=2)
    plt.show()

raise_plt()